#include <iostream>
#include <SDL/SDL.h>
#include "tbb/task_scheduler_init.h"
#include "tbb/tick_count.h"

#include "mandelbrot.hh"
#include "common.hh"





void Mandelbrot (SDL_Surface*	affichage)
{
  double minJ = -2.0;
  double maxJ = 1.0;
  double minI = -1.2;
  double maxI = minI + (maxJ - minJ) * HEIGHT / WIDTH;
  double jFactor = (maxJ - minJ) / (WIDTH - 1);
  double iFactor = (maxI - minI) / (HEIGHT - 1);


  //Begining Tick
  tbb::tick_count  t0 = tbb::tick_count::now();


  for (unsigned i = 0; i < HEIGHT; ++i)
    {
      double currentI = maxI - i * iFactor;

      for (unsigned j = 0; j < WIDTH; ++j)
	{
	  double currentJ = minJ + j * jFactor;

	  double zI = currentI;
	  double zJ = currentJ;

	  bool isInside = true;

	  for (unsigned iter = 0; iter < MAX_ITER; ++iter)
	    {
	      double zI2 = zI * zI;
	      double zJ2 = zJ * zJ;

	      if (zI2 + zJ2 > 4)
		{
		  isInside = false;
		  if (iter < MAX_ITER / 2)
		    setPixel(affichage, j, i, SDL_MapRGB(affichage->format,
							 0,
							 0,
							 iter * 511 / MAX_ITER));
		  else
		    setPixel(affichage, j, i, SDL_MapRGB(affichage->format,
							 (iter - MAX_ITER / 2) * 511 / MAX_ITER,
							 (iter - MAX_ITER / 2) * 511 / MAX_ITER,
							 255));
		  break;
		}

	      zI = 2 * zJ * zI + currentI;
	      zJ = zJ2 - zI2 + currentJ;
	    }
	  if (isInside)
	    {
	      setPixel(affichage, j, i,
		       SDL_MapRGB(affichage->format, 0, 0, 0));
	    }
	}
    }

  //Final Tick
  tbb::tick_count  t1 = tbb::tick_count::now();

  std::cout << (t1 - t0).seconds() << "s" << std::endl;
}
